Page({
  data: {
    balance: 1200.00,
    formattedBalance: '1200.00',
    pendingRewards: 280.08,
    distributorInfo: null,
    swipeLeft: 0, // 滑动距离
    startX: 0, // 触摸开始位置
    isSwiping: false, // 是否正在滑动
    activeTab: 'all', // 当前选中的标签：all, income, expense
    statusBarHeight: 44, // 状态栏高度
    navbarHeight: 88, // 导航栏高度
    totalNavbarHeight: 132, // 总高度
    transactions: []
  },
  
  onLoad() {
    // 获取系统信息，设置状态栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    const navbarHeight = 88 // 导航栏高度（rpx转px约为44px）
    const totalHeight = statusBarHeight + navbarHeight
    
    this.setData({
      statusBarHeight: statusBarHeight,
      navbarHeight: navbarHeight,
      totalNavbarHeight: totalHeight
    })
    
    this.loadWalletInfo()
  },
  
  // 返回上一页
  goBack() {
    wx.navigateBack()
  },
  
  onShow() {
    this.loadWalletInfo()
    // 重置滑动状态
    this.setData({
      swipeLeft: 0,
      isSwiping: false
    })
  },
  
  loadWalletInfo() {
    // 加载分销商信息
    const distributorInfo = wx.getStorageSync('distributorInfo') || null
    if (distributorInfo && distributorInfo.registerTime) {
      // 格式化注册时间
      const date = new Date(distributorInfo.registerTime)
      distributorInfo.formattedTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
    this.setData({ distributorInfo })
    
    // 加载钱包信息（这里可以从本地存储或后端获取）
    const walletInfo = wx.getStorageSync('walletInfo')
    if (walletInfo) {
      this.setData({
        balance: walletInfo.balance || 0,
        pendingRewards: walletInfo.pendingRewards || 0,
        formattedBalance: (walletInfo.balance || 0).toFixed(2)
      })
    } else {
      // 格式化默认余额
      this.setData({
        formattedBalance: this.data.balance.toFixed(2)
      })
    }
    
    // 加载交易记录
    this.loadTransactions()
  },
  
  // 加载交易记录
  loadTransactions() {
    const app = getApp()
    const orders = app.globalData.orders || []
    
    // 尝试从本地存储加载订单
    let localOrders = []
    try {
      localOrders = wx.getStorageSync('orders') || []
    } catch (e) {
      console.error('从本地存储加载订单失败:', e)
    }
    
    // 合并所有订单
    const allOrders = [...orders, ...localOrders]
    
    // 生成交易记录（从订单中提取返佣记录）
    const transactions = []
    
    // 如果订单数据为空，使用示例数据
    if (allOrders.length === 0) {
      transactions.push(
        {
          id: 1,
          type: 'order_commission',
          orderNo: '093132387126',
          amount: 11.90,
          date: '2019-06-19 08:21:09',
          tab: 'income'
        },
        {
          id: 2,
          type: 'order_commission',
          orderNo: '093132387931',
          amount: 10.09,
          date: '2019-06-19 08:21:09',
          tab: 'income'
        },
        {
          id: 3,
          type: 'withdraw',
          amount: -100.00,
          date: '2019-06-19 08:21:09',
          tab: 'expense'
        }
      )
    } else {
      // 从订单数据中生成交易记录
      allOrders.forEach((order, index) => {
        if (order.status === 'paid' || order.status === 'traveling' || order.status === 'completed' || order.status === 'reviewing') {
          // 计算返佣金额（假设为订单金额的1%）
          const commission = order.totalPrice ? (order.totalPrice * 0.01) : 0
          
          transactions.push({
            id: transactions.length + 1,
            type: 'order_commission',
            orderNo: order.orderNumber || order.orderNo || `ORD${order.id}`,
            orderId: order.id, // 添加订单ID
            amount: commission,
            date: order.createTime || new Date().toLocaleString('zh-CN'),
            tab: 'income'
          })
        }
      })
      
      // 添加提现记录（示例）
      transactions.push({
        id: transactions.length + 1,
        type: 'withdraw',
        amount: -100.00,
        date: '2019-06-19 08:21:09',
        tab: 'expense'
      })
    }
    
    this.setData({
      transactions: transactions
    })
  },
  
  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      activeTab: tab
    })
  },
  
  // 获取过滤后的交易记录
  getFilteredTransactions() {
    const { transactions, activeTab } = this.data
    if (activeTab === 'all') {
      return transactions
    }
    return transactions.filter(item => item.tab === activeTab)
  },
  
  // 提现
  withdraw() {
    wx.navigateTo({
      url: '/pages/withdraw/withdraw'
    })
  },
  
  // 查看分销规则
  goToDistributionRules() {
    wx.navigateTo({
      url: '/pages/distribution-rules/distribution-rules'
    })
  },
  
  // 查看订单详情
  goToOrderDetail(e) {
    const orderNo = e.currentTarget.dataset.orderNo
    const orderId = e.currentTarget.dataset.orderId
    
    if (!orderNo) {
      wx.showToast({
        title: '订单编号不存在',
        icon: 'none'
      })
      return
    }
    
    const app = getApp()
    const orders = app.globalData.orders || []
    
    // 尝试从本地存储加载订单
    let localOrders = []
    try {
      localOrders = wx.getStorageSync('orders') || []
    } catch (e) {
      console.error('从本地存储加载订单失败:', e)
    }
    
    // 合并全局订单和本地订单
    const allOrders = [...orders, ...localOrders]
    
    let targetOrder = null
    
    // 如果有订单ID，优先通过ID查找
    if (orderId) {
      targetOrder = allOrders.find(o => o.id === orderId || o.id === parseInt(orderId))
    }
    
    // 如果没有找到，通过订单编号查找
    if (!targetOrder) {
      targetOrder = allOrders.find(o => o.orderNumber === orderNo || o.orderNo === orderNo)
    }
    
    if (targetOrder && targetOrder.id) {
      // 找到订单，跳转到订单详情
      wx.navigateTo({
        url: `/pages/order-detail/order-detail?id=${targetOrder.id}&status=${targetOrder.status || 'pending'}`
      })
    } else {
      // 未找到订单，提示用户
      wx.showToast({
        title: '未找到该订单',
        icon: 'none',
        duration: 2000
      })
    }
  },
  
  // 查看奖金详情 - 跳转到奖励进度页面
  goToRewardsDetail() {
    wx.navigateTo({
      url: '/pages/reward-progress/reward-progress'
    })
  },
  
  // 触摸开始
  onTouchStart(e) {
    this.setData({
      startX: e.touches[0].clientX,
      isSwiping: true
    })
  },
  
  // 触摸移动
  onTouchMove(e) {
    if (!this.data.isSwiping) return
    
    const currentX = e.touches[0].clientX
    const diff = this.data.startX - currentX
    
    // 只允许向左滑动
    if (diff > 0) {
      // 将px转换为rpx (假设屏幕宽度为375px，750rpx)
      const systemInfo = wx.getSystemInfoSync()
      const pxToRpx = 750 / systemInfo.windowWidth
      const swipeLeftRpx = diff * pxToRpx
      
      // 限制最大滑动距离为200rpx
      const maxSwipe = 200
      const swipeLeft = Math.min(swipeLeftRpx, maxSwipe)
      this.setData({ swipeLeft })
    } else {
      // 向右滑动时恢复
      this.setData({ swipeLeft: 0 })
    }
  },
  
  // 触摸结束
  onTouchEnd(e) {
    const { swipeLeft } = this.data
    
    // 如果滑动距离超过100rpx，显示删除按钮
    if (swipeLeft > 100) {
      this.setData({ swipeLeft: 200 })
    } else {
      // 否则恢复原状
      this.setData({ swipeLeft: 0 })
    }
    
    this.setData({ isSwiping: false })
  },
  
  // 取消滑动
  cancelSwipe() {
    this.setData({
      swipeLeft: 0,
      isSwiping: false
    })
  },
  
  // 删除分销商信息
  deleteDistributor() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除分销商信息吗？删除后需要重新注册。',
      success: (res) => {
        if (res.confirm) {
          // 删除分销商信息
          wx.removeStorageSync('distributorInfo')
          
          wx.showToast({
            title: '已删除',
            icon: 'success'
          })
          
          // 重新加载数据（会自动显示注册入口）
          this.loadWalletInfo()
          
          // 重置滑动状态
          this.setData({
            swipeLeft: 0,
            isSwiping: false
          })
        } else {
          // 取消删除时也恢复滑动状态
          this.setData({
            swipeLeft: 0,
            isSwiping: false
          })
        }
      }
    })
  },
  
  // 跳转到注册分销商页面
  goToDistributorRegister() {
    wx.navigateTo({
      url: '/pages/distributor-register/distributor-register'
    })
  }
})

